package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.Comment;
import com.icefish.bean.Good;
import com.icefish.bean.fastjsonParse.getGoodAndCommnent.GoodAndComment;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.getGoodAndCommnent.GetGoodAndCommentResp;
import com.icefish.dao.CommentDao;
import com.icefish.dao.GoodDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/getGoodAndComment")
public class getGoodAndComment extends HttpServlet {
    private CommentDao commentDao = DaoFactory.getCommentDaoInstance();
    private GoodDao goodDao = DaoFactory.getGoodDaoInstance();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 标准配置
        Init_Req_Resp_Config.init(request, response);
        //从域中获取用户id
        Integer goodId = Integer.valueOf(request.getParameter("goods_id"));

        GetGoodAndCommentResp getGoodAndCommentResp = new GetGoodAndCommentResp();
        GoodAndComment gac = null;
        Boolean flag = null;

        try {
            //获取商品和评论信息
            Good good = goodDao.selectGoodByGoodId(goodId);
            ArrayList<Comment> comments=commentDao.selectCommentByGoodId(goodId);

            //创建javabean对象获取商品和评论信息
             gac = new GoodAndComment(good,comments);

            flag = true;

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (flag == true){
            //如果数据获取正常，创建meta对象并赋值给getGoodAndCommentResp的Meta部分
            Meta meta = new Meta("获取商品信息成功",200);
            getGoodAndCommentResp.setMeta(meta);
            getGoodAndCommentResp.setData(gac);
        }
        else {
            // 获取失败
            Meta meta = new Meta("获取商品信息失败",500);
            getGoodAndCommentResp.setMeta(meta);
        }

        //相应Json数据
        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(getGoodAndCommentResp);

        // 响应数据
        response.getWriter().write(backToBrowser);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
